package com.yupi.referral.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.referral.annotation.AuthCheck;
import com.yupi.referral.common.BaseResponse;
import com.yupi.referral.common.DeleteRequest;
import com.yupi.referral.common.ErrorCode;
import com.yupi.referral.common.ResultUtils;
import com.yupi.referral.constant.UserConstant;
import com.yupi.referral.exception.BusinessException;
import com.yupi.referral.exception.ThrowUtils;
import com.yupi.referral.model.dto.referral.*;
import com.yupi.referral.model.entity.Referral;
import com.yupi.referral.model.entity.User;
import com.yupi.referral.model.vo.ReferralVO;
import com.yupi.referral.service.ReferralService;
import com.yupi.referral.service.UserService;

import com.zretc.security.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
//import com.zretc.security.entity.LoginUser;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 内推接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/referral")
@Slf4j
public class ReferralController {

    @Resource
    private ReferralService referralService;

//    @Resource
//    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param referralAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addReferral(@RequestBody ReferralAddRequest referralAddRequest, HttpServletRequest request) {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        LoginUser user = (LoginUser) authentication.getPrincipal();
//        System.out.println(user.getUser());
        if (referralAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Referral referral = new Referral();
        BeanUtils.copyProperties(referralAddRequest, referral);
        List<String> tags = referralAddRequest.getTags();
        if (tags != null) {
            referral.setTags(JSONUtil.toJsonStr(tags));
        }
        referralService.validReferral(referral, true);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        referral.setUserId(user.getUser().getUserId());
        boolean result = referralService.save(referral);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newReferralId = referral.getId();
        return ResultUtils.success(newReferralId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteReferral(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        long id = deleteRequest.getId();
        // 判断是否存在
        Referral oldReferral = referralService.getById(id);
        ThrowUtils.throwIf(oldReferral == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldReferral.getUserId().equals(user.getUser().getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = referralService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param referralUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateReferral(@RequestBody ReferralUpdateRequest referralUpdateRequest) {
        if (referralUpdateRequest == null || referralUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Referral referral = new Referral();
        BeanUtils.copyProperties(referralUpdateRequest, referral);
        List<String> tags = referralUpdateRequest.getTags();
        if (tags != null) {
            referral.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        referralService.validReferral(referral, false);
        long id = referralUpdateRequest.getId();
        // 判断是否存在
        Referral oldReferral = referralService.getById(id);
        ThrowUtils.throwIf(oldReferral == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = referralService.updateById(referral);
        return ResultUtils.success(result);
    }

    /**
     * 审核通过
     *
     * @param referralState1Request
     * @return
     */
    @PostMapping("/setstate1")
    public BaseResponse<Boolean> setstate1(@RequestBody ReferralState1Request referralState1Request) {
        if (referralState1Request == null || referralState1Request.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long id = referralState1Request.getId();
        Referral oldReferral = referralService.getById(id);
        ThrowUtils.throwIf(oldReferral == null, ErrorCode.NOT_FOUND_ERROR);

        Referral referral = new Referral();
        BeanUtils.copyProperties(referralState1Request, referral);
        referral.setState(1);

        boolean result = referralService.updateById(referral);

        return ResultUtils.success(result);
    }


    /**
     * 审核不通过
     *
     * @param referralState2Request
     * @return
     */
    @PostMapping("/setstate2")
    public BaseResponse<Boolean> setstate2(@RequestBody ReferralState2Request referralState2Request) {
        if (referralState2Request == null || referralState2Request.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        long id = referralState2Request.getId();
        Referral oldReferral = referralService.getById(id);
        ThrowUtils.throwIf(oldReferral == null, ErrorCode.NOT_FOUND_ERROR);

        Referral referral = new Referral();
        BeanUtils.copyProperties(referralState2Request, referral);
        referral.setState(2);

        boolean result = referralService.updateById(referral);

        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ReferralVO> getReferralVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Referral referral = referralService.getById(id);
        if (referral == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(referralService.getReferralVO(referral, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param referralQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Referral>> listReferralByPage(@RequestBody ReferralQueryRequest referralQueryRequest) {
        long current = referralQueryRequest.getCurrent();
        long size = referralQueryRequest.getPageSize();
        Page<Referral> referralPage = referralService.page(new Page<>(current, size),
                referralService.getQueryWrapper(referralQueryRequest));
        return ResultUtils.success(referralPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param referralQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ReferralVO>> listReferralVOByPage(@RequestBody ReferralQueryRequest referralQueryRequest,
            HttpServletRequest request) {
//        referralQueryRequest.setState(1);
        long current = referralQueryRequest.getCurrent();
        long size = referralQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Referral> referralPage = referralService.page(new Page<>(current, size),
                referralService.getQueryWrapper(referralQueryRequest));
        return ResultUtils.success(referralService.getReferralVOPage(referralPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param referralQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ReferralVO>> listMyReferralVOByPage(@RequestBody ReferralQueryRequest referralQueryRequest,
            HttpServletRequest request) {
        if (referralQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        referralQueryRequest.setUserId(user.getUser().getUserId());
        long current = referralQueryRequest.getCurrent();
        long size = referralQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Referral> referralPage = referralService.page(new Page<>(current, size),
                referralService.getQueryWrapper(referralQueryRequest));
        return ResultUtils.success(referralService.getReferralVOPage(referralPage, request));
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param referralEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editReferral(@RequestBody ReferralEditRequest referralEditRequest, HttpServletRequest request) {
        if (referralEditRequest == null || referralEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Referral referral = new Referral();
        BeanUtils.copyProperties(referralEditRequest, referral);
        List<String> tags = referralEditRequest.getTags();
        if (tags != null) {
            referral.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        referralService.validReferral(referral, false);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        long id = referralEditRequest.getId();
        // 判断是否存在
        Referral oldReferral = referralService.getById(id);
        ThrowUtils.throwIf(oldReferral == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldReferral.getUserId().equals(user.getUser().getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = referralService.updateById(referral);
        return ResultUtils.success(result);
    }

}
